package com.allqj.sfx.domain.service;

import com.allqj.sfx.domain.cache.ICache;
import com.allqj.sfx.domain.entity.UserInfo;
import com.allqj.sfx.domain.utils.UserContextHolder;
import com.allqj.sfx.infrastructure.enums.ResultStatusCodeEnum;
import com.allqj.sfx.infrastructure.exceptions.BusinessException;
import com.allqj.sfx.infrastructure.utils.JsonUtil;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author sjw
 * @className TokenService
 * @date 2022/7/20 17:11
 * @description: token服务
 */

@Component
public class AuthenticationService {
    private ICache cache;

    public AuthenticationService(ICache cache) {
        this.cache = cache;
    }

    public String token(UserInfo userInfo) {
        if (userInfo == null || userInfo.getUserId() == null || userInfo.getDomainTypeEnum() == null) loginError();
        String token = userInfo.getDomainTypeEnum().getAppName() + userInfo.getUserId();
        cache.set(token, JsonUtil.objectToJson(userInfo), 5, TimeUnit.DAYS);
        return token;
    }

    public void validate(String token) {
        String value = cache.get(token);
        if (value == null) loginError();
        UserInfo userInfo = JsonUtil.jsonToObject(value, UserInfo.class);
        if (userInfo == null) {
            cache.delete(token);
            loginError();
        }
        UserContextHolder.setUserContext(userInfo);
    }

    private void loginError() {
        throw new BusinessException(ResultStatusCodeEnum.NOT_LOGIN.getCode(), ResultStatusCodeEnum.NOT_LOGIN.getMessage());
    }
}
